package com.example.listener;

import com.example.jobs.*;
import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;

@Component
public class StartApplicationListener implements ApplicationListener<ContextRefreshedEvent> {

    @Autowired
    private Scheduler scheduler;

    @Override
    public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
        TriggerKey quartzJobTriggerKey = TriggerKey.triggerKey("quartzTrigger", "quartzTrigger-group");
        TriggerKey hourJobTriggerKey = TriggerKey.triggerKey("hourTrigger", "hourTrigger-group");
        TriggerKey secondJobTriggerKey = TriggerKey.triggerKey("secondTrigger", "secondTrigger-group");
        TriggerKey minuteJobTriggerKey = TriggerKey.triggerKey("minuteTrigger", "minuteTrigger-group");
        TriggerKey timerJobTriggerKey = TriggerKey.triggerKey("timerTrigger", "timerTrigger-group");
        startScheduler(
                quartzJobTriggerKey,
                "quartzJob",
                "quartzJob-group",
                "0 0/1 * * * ?",
                QuartzJob.class
        );
        startScheduler(
                hourJobTriggerKey,
                "hourJob",
                "hourJob-group",
                "0 0 0/1 * * ?",
                HourJob.class
        );
        startScheduler(
                secondJobTriggerKey,
                "secondJob",
                "secondJob-group",
                "0/5 * * * * ?",
                SecJob.class
        );
        startScheduler(
                minuteJobTriggerKey,
                "minuteJob",
                "minuteJob-group",
                "0 0/2 * * * ?",
                MinJob.class
        );
        startScheduler(
                timerJobTriggerKey,
                "timerJob",
                "timerJob-group",
                "0 30 1 * * ?",
                TimerJob.class
        );
    }

    public void startScheduler(TriggerKey triggerKey, String jobName, String jobGroup, String cron, Class c) {
        try {
            Trigger trigger = scheduler.getTrigger(triggerKey);
            if (trigger == null) {
                trigger = TriggerBuilder.newTrigger()
                        .withIdentity(triggerKey)
                        .withSchedule(CronScheduleBuilder.cronSchedule(cron))
                        .startNow()
                        .build();

                JobDetail jobDetail = JobBuilder.newJob(c)
                        .withIdentity(jobName, jobGroup)
                        .build();

                scheduler.scheduleJob(jobDetail, trigger);
                scheduler.start();
            }
        } catch (SchedulerException e) {
            e.printStackTrace();
        }
    }
}
